
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>约束参考 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="模型 _meta API" href="meta.html" />
    <link rel="prev" title="模型索引参考" href="indexes.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="indexes.html" title="模型索引参考">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="meta.html" title="模型 &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;_meta&lt;/span&gt;&lt;/code&gt; API">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-models-constraints">
            
  <div class="section" id="s-module-django.db.models.constraints">
<span id="s-constraints-reference"></span><span id="module-django.db.models.constraints"></span><span id="constraints-reference"></span><h1>约束参考<a class="headerlink" href="#module-django.db.models.constraints" title="永久链接至标题">¶</a></h1>
<p>本模块中定义的类可以创建数据库约束。它们被添加到模型中 <code class="xref py py-attr docutils literal notranslate"><span class="pre">Meta.constraints</span></code> 选项中。</p>
<div class="admonition-referencing-built-in-constraints admonition">
<p class="first admonition-title">引用内置约束</p>
<p class="last">约束是在 <code class="docutils literal notranslate"><span class="pre">django.db.models.constraint</span></code> 中定义的，但为了方便，它们被导入到 <a class="reference internal" href="../../topics/db/models.html#module-django.db.models" title="django.db.models"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.db.models</span></code></a> 中。标准的惯例是使用 <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">django.db</span> <span class="pre">import</span> <span class="pre">models</span></code> 作为 <code class="docutils literal notranslate"><span class="pre">models.&lt;Foo&gt;Constraint</span></code>。</p>
</div>
<div class="admonition-constraints-in-abstract-base-classes admonition">
<p class="first admonition-title">抽象基类中的约束</p>
<p class="last">你必须始终为约束指定一个唯一的名称。因此，你通常不能在抽象基类上指定一个约束，因为 <code class="xref py py-attr docutils literal notranslate"><span class="pre">Meta.craces</span></code> 选项是由子类继承的，每次的属性值（包括 <code class="docutils literal notranslate"><span class="pre">name</span></code>）都完全相同。为了解决名称碰撞的问题，名称的一部分可能包含 <code class="docutils literal notranslate"><span class="pre">'%(app_label)s'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'%(class)s'</span></code>，它们分别被具体模型的小写应用标签和类名所代替。例如 <code class="docutils literal notranslate"><span class="pre">CheckConstraint(check=Q(age__gte=18)，name='%(app_label)s_%(class)s_is_adult')</span></code>。</p>
</div>
<div class="admonition-validation-of-constraints admonition">
<p class="first admonition-title">约束的验证</p>
<p class="last">一般来说，在 <code class="docutils literal notranslate"><span class="pre">full_clean()</span></code> 期间，约束条件 <strong>不会被</strong> 检查，也不会引起 <code class="docutils literal notranslate"><span class="pre">ValidationError</span></code>。而是在 <code class="docutils literal notranslate"><span class="pre">save()</span></code> 时，你会得到一个数据库完整性错误。没有 <a class="reference internal" href="#django.db.models.UniqueConstraint.condition" title="django.db.models.UniqueConstraint.condition"><code class="xref py py-attr docutils literal notranslate"><span class="pre">condition</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">UniqueConstraint</span></code> （即非部分唯一约束）在这方面是不同的，它们利用了现有的 <code class="docutils literal notranslate"><span class="pre">validate_unique()</span></code> 逻辑，从而实现了两阶段验证。除了在 <code class="docutils literal notranslate"><span class="pre">save()</span></code> 上出现 <code class="docutils literal notranslate"><span class="pre">IntegrityError</span></code> 外，在模型验证过程中，当 <code class="docutils literal notranslate"><span class="pre">UniqueConstraint</span></code> 被违反时，<code class="docutils literal notranslate"><span class="pre">ValidationError</span></code> 也会被引发。</p>
</div>
<div class="section" id="s-checkconstraint">
<span id="checkconstraint"></span><h2><code class="docutils literal notranslate"><span class="pre">CheckConstraint</span></code><a class="headerlink" href="#checkconstraint" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.db.models.CheckConstraint">
<em class="property">class </em><code class="descname">CheckConstraint</code>(<em>*</em>, <em>check</em>, <em>name</em>)<a class="headerlink" href="#django.db.models.CheckConstraint" title="永久链接至目标">¶</a></dt>
<dd><p>在数据库中创建一个检查约束</p>
</dd></dl>

<div class="section" id="s-check">
<span id="check"></span><h3><code class="docutils literal notranslate"><span class="pre">check</span></code><a class="headerlink" href="#check" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.CheckConstraint.check">
<code class="descclassname">CheckConstraint.</code><code class="descname">check</code><a class="headerlink" href="#django.db.models.CheckConstraint.check" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 <a class="reference internal" href="querysets.html#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span></code></a> 对象或布尔值 <a class="reference internal" href="expressions.html#django.db.models.Expression" title="django.db.models.Expression"><code class="xref py py-class docutils literal notranslate"><span class="pre">Expression</span></code></a>，它指定了你要强制约束的检查。</p>
<p>例如，<code class="docutils literal notranslate"><span class="pre">CheckConstraint(check=Q(age__gte=18),</span> <span class="pre">name='age_gte_18')</span></code> 确保年龄字段永远不小于 18。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>增加了对布尔 <a class="reference internal" href="expressions.html#django.db.models.Expression" title="django.db.models.Expression"><code class="xref py py-class docutils literal notranslate"><span class="pre">Expression</span></code></a> 的支持。</p>
</div>
</div>
<div class="section" id="s-name">
<span id="name"></span><h3><code class="docutils literal notranslate"><span class="pre">name</span></code><a class="headerlink" href="#name" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.CheckConstraint.name">
<code class="descclassname">CheckConstraint.</code><code class="descname">name</code><a class="headerlink" href="#django.db.models.CheckConstraint.name" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>约束的名称。你必须始终为约束指定一个唯一的名称。</p>
</div>
</div>
<div class="section" id="s-uniqueconstraint">
<span id="uniqueconstraint"></span><h2><code class="docutils literal notranslate"><span class="pre">UniqueConstraint</span></code><a class="headerlink" href="#uniqueconstraint" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.db.models.UniqueConstraint">
<em class="property">class </em><code class="descname">UniqueConstraint</code>(<em>*</em>, <em>fields</em>, <em>name</em>, <em>condition=None</em>, <em>deferrable=None</em>, <em>include=None</em>, <em>opclasses=()</em>)<a class="headerlink" href="#django.db.models.UniqueConstraint" title="永久链接至目标">¶</a></dt>
<dd><p>在数据库中创建一个唯一约束。</p>
</dd></dl>

<div class="section" id="s-fields">
<span id="fields"></span><h3><code class="docutils literal notranslate"><span class="pre">fields</span></code><a class="headerlink" href="#fields" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.UniqueConstraint.fields">
<code class="descclassname">UniqueConstraint.</code><code class="descname">fields</code><a class="headerlink" href="#django.db.models.UniqueConstraint.fields" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个字段名的列表，它指定了你要强制约束的唯一列集。</p>
<p>例如，<code class="docutils literal notranslate"><span class="pre">UniqueConstraint(field=['room',</span> <span class="pre">'date'],</span> <span class="pre">name='unique_booking')</span></code> 确保每个房间在每个日期只能被预订一次。</p>
</div>
<div class="section" id="s-id1">
<span id="id1"></span><h3><code class="docutils literal notranslate"><span class="pre">name</span></code><a class="headerlink" href="#id1" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.UniqueConstraint.name">
<code class="descclassname">UniqueConstraint.</code><code class="descname">name</code><a class="headerlink" href="#django.db.models.UniqueConstraint.name" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>约束的名称。你必须始终为约束指定一个唯一的名称。</p>
</div>
<div class="section" id="s-condition">
<span id="condition"></span><h3><code class="docutils literal notranslate"><span class="pre">condition</span></code><a class="headerlink" href="#condition" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.UniqueConstraint.condition">
<code class="descclassname">UniqueConstraint.</code><code class="descname">condition</code><a class="headerlink" href="#django.db.models.UniqueConstraint.condition" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 <a class="reference internal" href="querysets.html#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span></code></a> 对象，用于指定你想要强制执行的约束条件。</p>
<p>例子：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">UniqueConstraint</span><span class="p">(</span><span class="n">fields</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;user&#39;</span><span class="p">],</span> <span class="n">condition</span><span class="o">=</span><span class="n">Q</span><span class="p">(</span><span class="n">status</span><span class="o">=</span><span class="s1">&#39;DRAFT&#39;</span><span class="p">),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;unique_draft_user&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>确保每个用户只有一份草稿。</p>
<p>这些条件与 <a class="reference internal" href="indexes.html#django.db.models.Index.condition" title="django.db.models.Index.condition"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Index.condition</span></code></a> 具有相同的数据库限制。</p>
</div>
<div class="section" id="s-deferrable">
<span id="deferrable"></span><h3><code class="docutils literal notranslate"><span class="pre">deferrable</span></code><a class="headerlink" href="#deferrable" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.UniqueConstraint.deferrable">
<code class="descclassname">UniqueConstraint.</code><code class="descname">deferrable</code><a class="headerlink" href="#django.db.models.UniqueConstraint.deferrable" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 3.1.</span> </div>
<p>设置该参数，可创建一个可推迟的唯一约束。接受的值是 <code class="docutils literal notranslate"><span class="pre">Deferrable.DEFERRED</span></code> 或 <code class="docutils literal notranslate"><span class="pre">Deferrable.IMMEDIATE</span></code>。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">Deferrable</span><span class="p">,</span> <span class="n">UniqueConstraint</span>

<span class="n">UniqueConstraint</span><span class="p">(</span>
    <span class="n">name</span><span class="o">=</span><span class="s1">&#39;unique_order&#39;</span><span class="p">,</span>
    <span class="n">fields</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;order&#39;</span><span class="p">],</span>
    <span class="n">deferrable</span><span class="o">=</span><span class="n">Deferrable</span><span class="o">.</span><span class="n">DEFERRED</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<p>默认情况下，约束条件是不推迟的。推迟的约束条件在事务结束前不会被强制执行。即时约束将在每条命令后立即执行。</p>
<div class="admonition-mysql-mariadb-and-sqlite admonition">
<p class="first admonition-title">MySQL，MariaDB 和 SQLite。</p>
<p class="last">在 MySQL、MariaDB 和 SQLite 上，可推迟的唯一约束被忽略，因为它们都不支持。</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">推迟的唯一约束可能导致 <a class="reference external" href="https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4">性能惩罚</a> 。</p>
</div>
</div>
<div class="section" id="s-include">
<span id="include"></span><h3><code class="docutils literal notranslate"><span class="pre">include</span></code><a class="headerlink" href="#include" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.UniqueConstraint.include">
<code class="descclassname">UniqueConstraint.</code><code class="descname">include</code><a class="headerlink" href="#django.db.models.UniqueConstraint.include" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p>一个包含在覆盖的唯一索引中的字段名称的列表或元组，作为非键列。这允许只用索引扫描，用于只选择包含的字段（ <a class="reference internal" href="#django.db.models.UniqueConstraint.include" title="django.db.models.UniqueConstraint.include"><code class="xref py py-attr docutils literal notranslate"><span class="pre">include</span></code></a> ）和只过滤唯一字段（ <a class="reference internal" href="#django.db.models.UniqueConstraint.fields" title="django.db.models.UniqueConstraint.fields"><code class="xref py py-attr docutils literal notranslate"><span class="pre">fields</span></code></a> ）的查询。</p>
<p>例子：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">UniqueConstraint</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;unique_booking&#39;</span><span class="p">,</span> <span class="n">fields</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;room&#39;</span><span class="p">,</span> <span class="s1">&#39;date&#39;</span><span class="p">],</span> <span class="n">include</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;full_name&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>将允许对 <code class="docutils literal notranslate"><span class="pre">room</span></code> 和 <code class="docutils literal notranslate"><span class="pre">date</span></code> 进行过滤，也可以选择 <code class="docutils literal notranslate"><span class="pre">full_name</span></code>，同时只从索引中获取数据。</p>
<p><code class="docutils literal notranslate"><span class="pre">include</span></code> 只在 PostgreSQL 上支持。</p>
<p>Non-key columns have the same database restrictions as <a class="reference internal" href="indexes.html#django.db.models.Index.include" title="django.db.models.Index.include"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Index.include</span></code></a>.</p>
</div>
<div class="section" id="s-opclasses">
<span id="opclasses"></span><h3><code class="docutils literal notranslate"><span class="pre">opclasses</span></code><a class="headerlink" href="#opclasses" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.UniqueConstraint.opclasses">
<code class="descclassname">UniqueConstraint.</code><code class="descname">opclasses</code><a class="headerlink" href="#django.db.models.UniqueConstraint.opclasses" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p>The names of the <a class="reference external" href="https://www.postgresql.org/docs/current/indexes-opclass.html">PostgreSQL operator classes</a> to use for
this unique index. If you require a custom operator class, you must provide one
for each field in the index.</p>
<p>例子：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">UniqueConstraint</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;unique_username&#39;</span><span class="p">,</span> <span class="n">fields</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;username&#39;</span><span class="p">],</span> <span class="n">opclasses</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;varchar_pattern_ops&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>creates a unique index on <code class="docutils literal notranslate"><span class="pre">username</span></code> using <code class="docutils literal notranslate"><span class="pre">varchar_pattern_ops</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">opclasses</span></code> 对于 PostgreSQL 以外的数据库来说是被忽略的。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">约束参考</a><ul>
<li><a class="reference internal" href="#checkconstraint"><code class="docutils literal notranslate"><span class="pre">CheckConstraint</span></code></a><ul>
<li><a class="reference internal" href="#check"><code class="docutils literal notranslate"><span class="pre">check</span></code></a></li>
<li><a class="reference internal" href="#name"><code class="docutils literal notranslate"><span class="pre">name</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#uniqueconstraint"><code class="docutils literal notranslate"><span class="pre">UniqueConstraint</span></code></a><ul>
<li><a class="reference internal" href="#fields"><code class="docutils literal notranslate"><span class="pre">fields</span></code></a></li>
<li><a class="reference internal" href="#id1"><code class="docutils literal notranslate"><span class="pre">name</span></code></a></li>
<li><a class="reference internal" href="#condition"><code class="docutils literal notranslate"><span class="pre">condition</span></code></a></li>
<li><a class="reference internal" href="#deferrable"><code class="docutils literal notranslate"><span class="pre">deferrable</span></code></a></li>
<li><a class="reference internal" href="#include"><code class="docutils literal notranslate"><span class="pre">include</span></code></a></li>
<li><a class="reference internal" href="#opclasses"><code class="docutils literal notranslate"><span class="pre">opclasses</span></code></a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="indexes.html"
                        title="上一章">模型索引参考</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="meta.html"
                        title="下一章">模型 <code class="docutils literal notranslate"><span class="pre">_meta</span></code> API</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/models/constraints.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="indexes.html" title="模型索引参考">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="meta.html" title="模型 &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;_meta&lt;/span&gt;&lt;/code&gt; API">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>